from segmentation import *
from PIL.Image import *
import cv2.cv as cv
import cv2
from watershedding import *

def boundaryPoints(image):
    boundaryPixels = list()
    boundaryPixels.extend(pixelsThroughLine(0,0, 0, image.shape[0]-1))
    boundaryPixels.extend(pixelsThroughLine(1,image.shape[0]-1, image.shape[1]-1, image.shape[0]-1))
    bottom = pixelsThroughLine(image.shape[1]-1,0,image.shape[1]-1, image.shape[0]-2)
    bottom.reverse()
    boundaryPixels.extend(bottom)
    left = pixelsThroughLine(1, 0,image.shape[1]-2,0)
    left.reverse()
    boundaryPixels.extend(left)
    return boundaryPixels

def snakePoints(boundaryPixels, N):
    snakePoints = []
    between = float(len(boundaryPixels)/float(N))
    for i in range(0,N):
        snakePoints.append(boundaryPixels[int(i*between)])
    return snakePoints

img = cv2.imread("Intermediary images/top_teeth_7.tif") 
img_gray = preprocessForWaterShed(img)
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
for rowIndex, row in enumerate(img_gray):
    for columnIndex, value in enumerate(row):
        image[rowIndex,columnIndex] = max(image[rowIndex,columnIndex] - value*0.12,0)
drawscaled(image, 1)
p = boundaryPoints(image)
bitmap = cv.CreateImageHeader((image.shape[1], image.shape[0]), cv.IPL_DEPTH_8U, 1)
cv.SetData(bitmap, image.tostring(), 
           image.dtype.itemsize * image.shape[1])
snake = snakePoints(p,35)
a=[0.095]
b=[0.15]
c=[0.075]
i = 0
while i<1000:
    snake = cv.SnakeImage(bitmap,snake,a,b,c,(19,19),(cv.CV_TERMCRIT_ITER,1, 0.01),1)
    i+=1
for (x,y) in snake:
    cv2.circle(image, (x,y),4,255,cv.CV_FILLED,8)